// 游戏状态变量
let score = 0;
let combo = 0;
let timeLeft = 60;
let gameInterval;
let moleInterval;
let isPlaying = false;
let lastHitTime = 0;
let difficulty = 1000; // 初始难度，地鼠出现间隔（毫秒）
let missCount = 0; // 错过地鼠次数
let gameMode = 'normal'; // 游戏模式
let difficultySettings = {
    easy: { interval: 1200, duration: 1000, maxMisses: 10 },
    normal: { interval: 1000, duration: 800, maxMisses: 5 },
    hard: { interval: 800, duration: 600, maxMisses: 3 }
};

// DOM 元素
let startScreen, scoreDisplay, comboDisplay, timeDisplay, missDisplay,
    restartButton, gameOverScreen, finalScoreDisplay, moles, holes,
    difficultyButtons, backToMenuButton, menuButton;

// 根据当前页面初始化DOM元素
function initializeDOMElements() {
    startScreen = document.getElementById('startScreen');
    scoreDisplay = document.getElementById('score');
    comboDisplay = document.getElementById('combo');
    timeDisplay = document.getElementById('time');
    missDisplay = document.getElementById('missCount');
    restartButton = document.getElementById('restartButton');
    gameOverScreen = document.getElementById('gameOver');
    finalScoreDisplay = document.getElementById('finalScore');
    moles = document.querySelectorAll('.mole');
    holes = document.querySelectorAll('.hole');
    difficultyButtons = document.querySelectorAll('[data-difficulty]');
    backToMenuButton = document.getElementById('backToMenu');
    menuButton = document.getElementById('menuButton');
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    initializeDOMElements();
    
    // 根据当前页面URL判断是否需要初始化游戏
    const urlParams = new URLSearchParams(window.location.search);
    const urlMode = urlParams.get('mode');
    if (urlMode && ['easy', 'normal', 'hard'].includes(urlMode)) {
        initGame(urlMode);
    }

    // 绑定事件监听器
    if (difficultyButtons) {
        difficultyButtons.forEach(button => {
            button.addEventListener('click', () => {
                const mode = button.dataset.difficulty;
                window.location.href = `game.html?mode=${mode}`;
            });
        });
    }

    if (restartButton) {
        restartButton.addEventListener('click', () => initGame(gameMode));
    }

    if (backToMenuButton) {
        backToMenuButton.addEventListener('click', () => {
            isPlaying = false;
            clearInterval(gameInterval);
            clearTimeout(moleInterval);
            window.location.href = 'index.html';
        });
    }

    if (menuButton) {
        menuButton.addEventListener('click', () => {
            gameOverScreen.classList.add('hidden');
            if (startScreen) startScreen.style.display = 'block';
        });
    }

    if (moles) {
        initializeMoleEvents();
        moles.forEach(mole => {
            mole.addEventListener('click', handleMoleClick);
        });
    }
});

// 音效元素
const hitSound = document.getElementById('hitSound');
const missSound = document.getElementById('missSound');
const comboSound = document.getElementById('comboSound');

// 初始化游戏
function initGame(mode) {
    score = 0;
    combo = 0;
    timeLeft = 60;
    missCount = 0;
    gameMode = mode;
    difficulty = difficultySettings[mode].interval;
    isPlaying = true;
    if (startScreen) startScreen.style.display = 'none';
    if (gameOverScreen) gameOverScreen.classList.add('hidden');
    if (mode !== 'easy' && document.querySelector('.misses')) {
        document.querySelector('.misses').classList.remove('hidden');
    }
    updateDisplays();
    startGameIntervals();
}

// 更新显示
function updateDisplays() {
    if (scoreDisplay) scoreDisplay.textContent = score;
    if (comboDisplay) comboDisplay.textContent = combo;
    if (timeDisplay) timeDisplay.textContent = timeLeft;
    if (missDisplay) missDisplay.textContent = missCount;
}

// 开始游戏定时器
function startGameIntervals() {
    // 倒计时
    gameInterval = setInterval(() => {
        timeLeft--;
        updateDisplays();
        if (timeLeft <= 0) {
            endGame();
        }
    }, 1000);

    // 地鼠出现
    showMole();
}

// 随机显示地鼠
function showMole() {
    if (!isPlaying) return;

    // 隐藏所有地鼠
    moles.forEach(mole => {
        mole.classList.remove('show');
        mole.classList.remove('hit');
    });

    // 随机选择一个洞
    const randomHole = Math.floor(Math.random() * holes.length);
    const mole = holes[randomHole].querySelector('.mole');
    mole.classList.add('show');

    // 设置地鼠消失时间
    setTimeout(() => {
        if (mole.classList.contains('show') && !mole.classList.contains('hit')) {
            mole.classList.remove('show');
            missSound.play().catch(e => console.log('音效播放失败'));
            combo = 0;
            if (gameMode !== 'easy') {
                missCount++;
                if (missCount >= difficultySettings[gameMode].maxMisses) {
                    endGame();
                    return;
                }
            }
            updateDisplays();
        }
    }, difficultySettings[gameMode].duration);

    // 设置下一个地鼠出现的时间
    moleInterval = setTimeout(showMole, difficultySettings[gameMode].interval);
}

// 点击地鼠
function initializeMoleEvents() {
    if (!moles) return;
    moles.forEach(mole => {
        mole.addEventListener('click', handleMoleClick);
    });
}

// 处理地鼠点击事件
function handleMoleClick() {
    if (!isPlaying || !this.classList.contains('show') || this.classList.contains('hit')) return;

    const currentTime = Date.now();
    const timeDiff = currentTime - lastHitTime;
    lastHitTime = currentTime;

    // 连击判定（3秒内）
    if (timeDiff < 3000) {
        combo++;
        if (combo > 1) {
            comboSound.play().catch(e => console.log('音效播放失败'));
        }
    } else {
        combo = 1;
    }

    // 计算得分（基础分 + 连击加成）
    const baseScore = 10;
    const comboBonus = Math.min(combo - 1, 5) * 5; // 最高5连击
    score += baseScore + comboBonus;

    // 更新显示
    this.classList.add('hit');
    this.classList.add('shake');
    hitSound.play().catch(e => console.log('音效播放失败'));
    updateDisplays();

    // 检查成就
    checkAchievements();

    // 移除动画效果
    setTimeout(() => {
        this.classList.remove('shake');
        this.classList.remove('show');
        this.classList.remove('hit');
    }, 300);
}

// 结束游戏
function endGame() {
    isPlaying = false;
    clearInterval(gameInterval);
    clearTimeout(moleInterval);
    finalScoreDisplay.textContent = score;
    gameOverScreen.classList.remove('hidden');

    // 检查成就
    checkAchievements();

    // 隐藏所有地鼠
    moles.forEach(mole => {
        mole.classList.remove('show');
        mole.classList.remove('hit');
    });
}